using System.Net;
using System.Text.Json.Serialization;
using System.Web;
using ef_core_2025_learn;
using ef_core_2025_learn.Entity;
using LinqToDB;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddControllers();
builder.Services.AddDbContext<MyBoardsContent>();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});

var app = builder.Build();


if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<MyBoardsContent>();
var pendingMigrations = dbContext.Database.GetPendingMigrations();
if (pendingMigrations.Any())
{
    dbContext.Database.Migrate();
}

var users = dbContext.Users.ToList();
if (users.Count == 0)
{
    var user1 = new User()
    {
        Email = "user1@test.com",
        FirstName = "user one",
        Address = new Address()
        {
            City = "warszwa",
            Street = "szeroka"
        }
    };

    var user2 = new User()
    {
        Email = "user2@test.com",
        FirstName = "user one2",
        Address = new Address()
        {
            City = "warszwa2",
            Street = "szeroka2"
        }
    };

    dbContext.Users.AddRange(user1, user2);
    dbContext.SaveChanges();
}

app.MapGet("/data", (MyBoardsContent db) =>
{
    var epic = new Epic()
    {
        Id = 2,
        Area = "ffff",
        IterationPath = "ddd",
        Priority = 1
    };
    var entityEntry = db.Attach(epic);


    return new {  };
});

app.MapPost("update", (MyBoardsContent db) =>
{
    var epic = db.Epics.First(epic => epic.Id == 1);



    var entityEntries1 = db.ChangeTracker.Entries();
    epic.Area = "onHoleState1";
    var entityEntries2 = db.ChangeTracker.Entries();

    db.SaveChanges();
});

app.MapPost("create", (MyBoardsContent db) =>
{
    var address = new Address
    {
        Id = Guid.NewGuid(),
        City = "城市"
    };
    var user = new User()
    {
        Email = "menin@1.com",
        FirstName = "ffff",
        Address = address
    };
    db.Users.Add(user);
    db.SaveChanges();
});

DataGenerator.Seed(dbContext);

app.Run();